package org.jiuling.aliyun.sms.factory.service.impl;


import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import org.jiuling.aliyun.sms.config.AliYunSmsConfig;
import org.jiuling.aliyun.sms.convert.SendSmsResponseConvert;
import org.jiuling.aliyun.sms.exception.AliYunSMSRuntimeException;
import org.jiuling.aliyun.sms.factory.AliYunSmsSynchronization;
import org.jiuling.aliyun.sms.factory.service.AliYunSendSmsService;
import org.jiuling.aliyun.sms.factory.service.verify.AliYunSendSmsVerify;
import org.jiuling.aliyun.sms.model.SendSmsResponseModel;

import java.util.List;
import java.util.Map;

/**
 * 阿里云同步发送短信服务实现类
 * @author 紫灵
 * @date 2023年02月09日 17时30分57秒
 */
public class AliYunSyncSendSmsServiceImpl extends AliYunSmsSynchronization implements AliYunSendSmsService {


    public AliYunSyncSendSmsServiceImpl(AliYunSmsConfig aliYunSmsConfig) {
        super(aliYunSmsConfig);
    }

    @Override
    public SendSmsResponseModel sendSms(String signName,String phoneNumber, String templateCode, Map<String, Object> templateParam) {
        // 校验发送短信参数
        AliYunSendSmsVerify.sendSmsParam(signName, phoneNumber, templateCode);
        try {
            // 封装短信发送请求
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(JSON.toJSONString(templateParam));
            // 构建客户端发送短信
            return SendSmsResponseConvert.bodyToModel(create()
                    .sendSms(sendSmsRequest).getBody());
        }catch (Exception e) {
            throw new AliYunSMSRuntimeException(e.getLocalizedMessage());
        }
    }

    @Override
    public SendSmsResponseModel sendBatchSms(List<String> signNameList,List<String> phoneNumberList, String templateCode, List<Map<String, Object>> templateParamList) {
        // 校验发送批量短信参数
        AliYunSendSmsVerify.sendBatchSmsParam(signNameList, phoneNumberList, templateCode, templateParamList);
        // 封装批量短信发送请求
        SendBatchSmsRequest sendBatchSmsRequest = new SendBatchSmsRequest()
                .setPhoneNumberJson(JSON.toJSONString(phoneNumberList))
                .setSignNameJson(JSON.toJSONString(signNameList))
                .setTemplateCode(templateCode)
                .setTemplateParamJson(JSON.toJSONString(templateParamList));
        try {
            // 构建客户端
            return SendSmsResponseConvert.bodyToModel(create()
                    .sendBatchSms(sendBatchSmsRequest).getBody());
        }catch (Exception e){
            throw new AliYunSMSRuntimeException(e.getLocalizedMessage());
        }
    }



}
